<template>
  <div class="dialog">
    <el-dialog
      :title="'备件入库'+titleText"
      :visible.sync="showDialog"
      width="60%"
      top="0"
      :close-on-click-modal="false"
      @close="cancel"
    >
      <el-table
        ref="rightTableData"
        :data="rightTableData"
        tooltip-effect="dark"
        border
        stripe
        highlight-current-row
        style="position: relative"
      >
        <el-table-column type="index" label="序号" width="50">
          <template slot-scope="scoped">
            {{ scoped.row.sparePartCode?scoped.$index+1:'' }}
          </template>
        </el-table-column>
        <el-table-column
          label="备件名称"
          prop="sparePartName"
          min-width="95"
          align="center"
        >
          <template slot-scope="scope">
            <el-select
              v-model="scope.row.sparePartCode"
              filterable
              clearable
              placeholder="请选择备件名称"
            >
              <el-option
                v-for="(item,index) of sparePartArr"
                :key="index+'sparePart'"
                :label="item.sparePartName"
                :value="item.sparePartCode"
              />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column
          label="入库数量"
          min-width="75"
          prop="num"
        >
          <template slot-scope="scope">
            <el-input
              v-model="scope.row.num"
              placeholder="数量"
              clearable
            />
          </template>
        </el-table-column>
        <el-table-column
          label="入库单价"
          min-width="75"
          prop="price"
        >
          <template slot-scope="scope">
            <el-input
              v-model="scope.row.price"
              placeholder="入库单价"
              clearable
            >
              <template slot="append">
                元
              </template>
            </el-input>
          </template>
        </el-table-column>
        <el-table-column label="入库总价" min-width="95" prop="total">
          <template slot-scope="scope">
            <el-input
              v-model="scope.row.total"
              placeholder="总价 = 单价 × 数量"
              clearable
            >
              <template slot="append">
                元
              </template>
            </el-input>
          </template>
        </el-table-column>
        <el-table-column v-if="nowChanceStau === 'add'" label="操作" min-width="40">
          <template slot-scope="scope">
            <el-button
              type="text"
              style="color:red;text-decoration: underline;"
              size="small"
              @click.native.prevent="
                deleteRow(scope.$index, rightTableData)
              "
            >
              删除
            </el-button>
          </template>
        </el-table-column>
        <template slot="empty">
          <div>请添加数据</div>
        </template>
      </el-table>
      <el-row>
        <el-button
          v-if="nowChanceStau === 'add'"
          type="info"
          plain
          icon="el-icon-circle-plus-outline"
          class="addInfo"
          @click="addButInfo"
        >
          添加
        </el-button>
      </el-row>
      <el-form
        ref="ruleForm"
        label-position="left"
        :model="formData"
        :rules="rules"
        class="el-form"
      >
        <el-form-item label="入库日期：" class="w50p" prop="ioTime">
          <el-date-picker
            v-model="formData.ioTime"
            type="date"
            placeholder="选择日期"
            value-format="yyyy-MM-dd"
            clearable
          />
        </el-form-item>
        <el-form-item label="入库人：" class="w50p" prop="username">
          <el-select
            v-model="formData.username"
            clearable
            filterable
            placeholder="请选择入库人"
          >
            <el-option
              v-for="(item,index) of userList"
              :key="index+'id'"
              :label="item.username"
              :value="item.username"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="入库仓库：" class="w50p" prop="storeHouseCode">
          <el-select
            v-model="formData.storeHouseCode"
            clearable
            filterable
            placeholder="请选择入库仓库"
          >
            <el-option
              v-for="(item,index) of storeHouseList"
              :key="index+'storeHouseCode'"
              :label="item.storeHouseName"
              :value="item.storeHouseCode"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="供应商：" class="w50p" prop="supplierName">
          <el-select
            v-model="formData.supplierId"
            clearable
            filterable
            placeholder="请选择供应商"
            @change="querySuppliersNameAndId"
          >
            <el-option
              v-for="(item,index) of supplierList"
              :key="index+item.supplierNo"
              :label="item.supplierName"
              :value="item.supplierId"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button class="cancelbtn" @click="cancel()">取 消</el-button>
        <el-button type="primary" class="savebtn" @click="save('ruleForm')">保 存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
// import MultipleUpimage from "@/components/uploadimage/MultipleUploadimage.vue";
import sparePartsInputApi from "@/api/spare-part-manage/spare-parts-input";
import warehouseManageApi from "@/api/spare-part-manage/warehouse-manage";
import sparePartModelApi from "@/api/spare-part-manage/spare-part-model";
import sparePartSupplierApi from "@/api/spare-part-manage/spare-part-supplier";

export default {
  name: '',
  components: {},
  props: {
    // 弹框名称
    titleText: {
      type: String,
      default: ""
    },
    nowChanceStau: {
      type: String,
      default: ""
    },
    show: {
      type: Boolean,
      default: false
    },
    editObject: {
      type: [Object],
      default: () => {
        return {}
      }
    },
    userList: {
      type: [Array],
      default: () => {
        return []
      }
    }
  },
  data() {
    return {
      formData: {},
      rules: {
        ioTime: [
          { required: true, message: "请选择日期", trigger: ["change", "blur"] }
        ],
        userId: [
          { required: true, message: "请选择入库人", trigger: ["change", "blur"] }
        ],
        storeHouseCode: [
          { required: true, message: "请选择入库仓库", trigger: ["change", "blur"] }
        ]
      },
      //供应商
      supplierList:[],
      // 仓库
      storeHouseList: [],
      showDialog: this.show,
      rightTableData: [],
      // 备件
      sparePartArr: []
    };
  },

  watch: {
    show(v) {
      this.showDialog = v;
    },
    nowChanceStau(v) {
      this.rightTableData = []
      if (v === 'add') {
        this.formData = {}
      }
      if (v === 'edit') {
        this.formData = this.editObject
        this.rightTableData = [{
          sparePartCode: this.editObject.sparePartCode,
          sparePartIOCode: this.editObject.sparePartIOCode,
          num: this.editObject.num,
          price: this.editObject.price,
          total: this.editObject.total }]
      }
    },
    rightTableData: {
      deep: true,
      handler(val) {
        val.forEach(item => {
          if (
            item.num &&
            item.price
          ) {
            item.total = (
              parseFloat(item.num) *
              parseFloat(item.price)
            ).toFixed(2);
          } else {
            item.total;
          }
        });
      }
    }
  },
  created() {
    this.queryStoreHouseList()
    this.querySparePartList()
    this.querySuppliers()
  },
  mounted() {
  },
  methods: {
    // 查询备件
    querySparePartList() {
      // 获取数据
      let param = {
        page: 1,
        size: 1000
      };
      sparePartModelApi.queryPageList(param).then(res => {
        if (res.code === 1) {
          let data = res.data || {};
          this.sparePartArr = data.content || [];
        }
      });
    },
    //查询可选择供应商
    querySuppliers(){
      sparePartSupplierApi.queryList({}).then(res=>{
        console.log(res);
        this.supplierList = res.data
      })
    },
    //
    querySuppliersNameAndId(e){
      this.supplierList.some(ele => {
        if(ele.supplierId === e){
          this.formData.supplierName = ele.supplierName
          return true
        }
      })
    },
    // 查询可选择仓库
    queryStoreHouseList() {
      warehouseManageApi.queryByOrganizationMarkList({}).then(res => {
        if (res.code === 1) {
          let data = res.data || []
          this.storeHouseList = data;
        }
      });
    },
    // // 获取图片的base64数组
    // contractImg(e) {
    //   this.contractPictureList = e;
    // },
    // 点击添加按按钮
    addButInfo() {
      let list = {
        sparePartCode: "",
        num: "",
        price: "",
        total: ""
      };
      this.rightTableData.unshift(list);
    },
    // 删除改行
    deleteRow(index, rows) {
      rows.splice(index, 1);
    },
    save(formData) {
      this.formData.total = Number(this.formData.total)
      this.$refs[formData].validate(valid => {
        if (valid) {
          if (this.nowChanceStau === "edit") {
            this.formData.input = true
            this.rightTableData.forEach(a => {
              let params = { ...this.formData, ...a };
              sparePartsInputApi.edit(params).then(res => {
                if (res.code === 1) {
                  this.$message.success("修改成功！");
                  this.close()
                } else {
                  this.$message.error(res.msg);
                }
              });
            })
          } else if (this.nowChanceStau === "add") {
            this.formData.input = true
            // if (this.contractPictureList) {
            //   this.formData.picture = this.contractPictureList;
            // }
            this.rightTableData.forEach(a => {
              let params = { ...this.formData, ...a };
              sparePartsInputApi.add(params).then(res => {
                if (res.code === 1) {
                  this.$message.success(res.msg);
                  this.close()
                } else {
                  this.$message.error(res.msg);
                }
              });
            })
          }
        } else {
          return false;
        }
      });
    },
    close() {
      this.$emit("closeDialog");
    },
    cancel() {
      this.$emit("cancelDialog");
    }
  }
};
</script>

<style lang="scss" scoped>
::v-deep .el-table th{
  color:#000;
  background-color: rgba(120, 182, 193, 0.4) !important;
}
::v-deep .el-table .el-table__row--striped{
  color:#000;
  background-color: rgba(186, 186, 186, 0.4) !important;
}
::v-deep.el-table td, .el-table th.is-leaf,.el-table--border, .el-table--group, .el-table th.is-leaf{
  border-color: #D3D3D3 !important;
}
::v-deep .el-table th.is-leaf{
  border-color: #D3D3D3 !important;
}
::v-deep .el-table__empty-text{
  color: #000;
}
::v-deep .el-table{
  color: #000;
}
.addInfo{
  width: 100%;
  margin: 10px;
  background-color: #006E91;
  color: #fff;
  font-size: 18px;

}
.el-form{
  margin-top: 10px;
}
</style>
